﻿using LinqKit;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using OConf.Common;
using OConf.Entity;
using OConf.IBLL;
using OConf.Model;
using OConf.Model.Common;
using OConf.Model.RequestInput.Users;
using OConf.Service;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace OConf.BLL
{
    public class AdminBLL: IAdminBLL
    {
        private readonly AdminService _adminService;
        private readonly LoginLogService _loginLogService;
        private IConfiguration _configuration { get; }
        public AdminBLL(IConfiguration configuration)
        {
            _configuration = configuration;
            _adminService = new AdminService(_configuration);
            _loginLogService = new LoginLogService(_configuration);
        }

        /// <summary>
        /// 获取管理员详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnData<UserDetailModel> GetUserDetail(string id)
        {
            try
            {
                AdminsEntity userEntity = _adminService.FindEntity(id);
                if (userEntity == null)
                {
                    return ReturnDataHelper<UserDetailModel>.NoExists("不存在该用户信息", null);
                }

                UserDetailModel usersModel = new UserDetailModel()
                {
                    ID = userEntity.ID,
                    AccountNumber = userEntity.AccountNumber,
                    UserName = userEntity.UserName,
                    Email = userEntity.Email,
                    RoleType = userEntity.RoleType
                };
                return ReturnDataHelper<UserDetailModel>.Success("操作成功", usersModel);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("获取管理员详情,GetUserDetail", ex);
                return ReturnDataHelper<UserDetailModel>.Exception("系统异常", null);
            }
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> RegisterUser(RegisterUserInput input)
        {
            try
            {
                if (_adminService.IsExistsByAccountNumber(input.AccountNumber))
                {
                    return ReturnDataHelper<bool>.Exists("账号已存在", false);
                }

                AdminsEntity entity = new AdminsEntity();
                entity.ID = Guid.NewGuid().ToString();
                entity.AccountNumber = input.AccountNumber;
                entity.UserName = input.UserName;
                entity.Password = "000000".MD5Encrypt();
                entity.Email = input.Email;
                entity.Createtime = DateTime.Now;
                entity.Enable = true;
                entity.RoleType = input.RoleType;

                _adminService.AddEntity(entity);

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("用户注册,RegisterUser", ex);
                return ReturnDataHelper<bool>.Exception("系统异常", false);
            }
        }

        /// <summary>
        /// 账号登录
        /// </summary>
        /// <param name="userAccount"></param>
        /// <param name="userPwd"></param>
        /// <returns></returns>
        public ReturnData<UserLoginResponse> UserLogin(string userAccount, string userPwd)
        {
            try
            {
                AdminsEntity userEntity = _adminService.GetUserByAccount(userAccount);
                if (userEntity == null)
                {
                    return ReturnDataHelper<UserLoginResponse>.NoExists("账号不存在", null);
                }
               
                if (userEntity.Password != userPwd.MD5Encrypt())
                {
                    return ReturnDataHelper<UserLoginResponse>.Fail("账号或密码错误", null);
                }
                if (!userEntity.Enable)
                {
                    return ReturnDataHelper<UserLoginResponse>.Fail("账号被禁用，登录失败", null);
                }

                UsersModel usersModel = new UsersModel()
                {
                    ID = userEntity.ID,
                    UserName = userEntity.UserName,
                    RoleType = userEntity.RoleType
                };
                string jwtToken = GetJWTToken(usersModel);
                HttpUnit.Current.Response.Headers["access-token"] = jwtToken;
                UserLoginResponse result = new UserLoginResponse()
                {
                    token = jwtToken
                };

                //记录登录日志
                LoginLogEntity loginLogEntity = new LoginLogEntity()
                {
                    ID = Guid.NewGuid().ToString("N"),
                    AccountNum = userAccount,
                    LoginIP = HttpUnit.GetIP(),
                    CreateTime = DateTime.Now
                };
                _loginLogService.AddEntity(loginLogEntity);

                return ReturnDataHelper<UserLoginResponse>.Success("登录成功", result);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("账号登录,UserLogin", ex);
                return ReturnDataHelper<UserLoginResponse>.Exception("系统异常", null);
            }
        }

        /// <summary>
        /// 获取JWTToken信息
        /// </summary>
        /// <param name="userModel"></param>
        /// <returns></returns>
        private string GetJWTToken(UsersModel userModel)
        {
            var claims = new[]
            {
                 new Claim("ID", userModel.ID),
                 new Claim("UserName", userModel.UserName),
                 new Claim("RoleType", userModel.RoleType.ToString())
            };
            //需要加密：需要加密key:
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWTTokenOptions:SecurityKey"]));

            //加密方式，这里该可以根据配置文件进行多种加密方式
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: _configuration["JWTTokenOptions:Issuer"],
                audience: _configuration["JWTTokenOptions:Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(Convert.ToDouble(_configuration["JWTTokenOptions:ExpiredTime"])),
                signingCredentials: creds
             );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        /// <summary>
        /// 用户修改密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> ModifyUserPassWord(EditPersionalPwdInput input)
        {
            try
            {
                string id = ManagerUnit.GetCurrentID();
                if (string.IsNullOrEmpty(id))
                {
                    return ReturnDataHelper<bool>.NeedLogin("请登录后再操作", false);
                }

                if (input.OldPwd == input.NewPwd)
                {
                    return ReturnDataHelper<bool>.Fail("新密码不能与旧密码一致", false);
                }

                AdminsEntity user = _adminService.FindEntity(id);

                if (user == null)
                {
                    return ReturnDataHelper<bool>.NoExists("用户信息不存在", false);
                }

                if (user.Password != input.OldPwd.MD5Encrypt())
                {
                    return ReturnDataHelper<bool>.Fail("密码验证失败", false);
                }

                _adminService.UpdateUserPwd(id, input.NewPwd.MD5Encrypt());

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("用户修改密码,ModifyUserPassWord", ex);
                return ReturnDataHelper<bool>.Exception("系统异常", false);
            }
        }

        /// <summary>
        /// 用户个人中心修改个人信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> ModifyUserSelfInfo(EditPersionalInfoInput input)
        {
            try
            {
                string id = ManagerUnit.GetCurrentID();
                if (string.IsNullOrEmpty(id))
                {
                    return ReturnDataHelper<bool>.NeedLogin("请登录后再操作", false);
                }

                AdminsEntity user = _adminService.FindEntity(id);
                if (user == null)
                {
                    return ReturnDataHelper<bool>.NoExists("用户信息不存在", false);
                }

                user.UserName = input.UserName;
                user.Email = input.Email;

                _adminService.UpdatePersonalInfo(user);

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("用户个人中心修改个人信息,ModifyUserSelfInfo", ex);
                return ReturnDataHelper<bool>.Exception("系统异常", false);
            }
        }

        /// <summary>
        /// 用户个人中心获取用户信息
        /// </summary>
        /// <returns></returns>
        public ReturnData<UserPersonalCenterModel> GetPersonalInfo()
        {
            try
            {
                string id = ManagerUnit.GetCurrentID();
                if (string.IsNullOrEmpty(id))
                {
                    return ReturnDataHelper<UserPersonalCenterModel>.NeedLogin("请登录后再进行操作", null);
                }

                var entity = _adminService.FindEntity(id);
                if (entity == null)
                {
                    return ReturnDataHelper<UserPersonalCenterModel>.NoExists("不存在该用户信息", null);
                }

                UserPersonalCenterModel result = new UserPersonalCenterModel()
                {
                    AccountNumber = entity.AccountNumber,
                    UserName = entity.UserName,
                    Email = entity.Email
                };

                return ReturnDataHelper<UserPersonalCenterModel>.Success("操作成功", result);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("用户个人中心获取用户信息,GetPersonalInfo", ex);
                return ReturnDataHelper<UserPersonalCenterModel>.Exception("系统异常", null);
            }
        }

        /// <summary>
        /// 管理后台用户分页查询
        /// </summary>
        /// <param name="queryParam"></param>
        /// <returns></returns>
        public ReturnData<ReturnTableData<UsersModel>> QueryPage(QueryUserInput queryParam)
        {
            ReturnTableData<UsersModel> result = new ReturnTableData<UsersModel>();
            ExpressionStarter<AdminsEntity> where = PredicateBuilder.New<AdminsEntity>(true);
            where = where.And(w => w.RoleType != (int)RoleTypeEnum.系统管理员);
            if (!string.IsNullOrEmpty(queryParam.AccountNumber))
            {
                where = where.And(w => w.AccountNumber == queryParam.AccountNumber);
            }
            if (!string.IsNullOrEmpty(queryParam.UserName))
            {
                where = where.And(w => w.UserName == queryParam.UserName);
            }
            try
            {
                var info = _adminService.QueryPage(queryParam.PageIndex, queryParam.PageSize, where);
                result.Total = info.Total;
                result.List = info.List.Select(w => new UsersModel()
                {
                    ID = w.ID,
                    AccountNumber = w.AccountNumber,
                    Password = w.Password,
                    UserName = w.UserName,
                    Email = w.Email,
                    Createtime = w.Createtime,
                    Enable = w.Enable,
                    RoleType = w.RoleType
                }).ToList();

                return ReturnDataHelper<ReturnTableData<UsersModel>>.Success("操作成功", result);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("管理后台用户分页查询,QueryPage", ex);
                return ReturnDataHelper<ReturnTableData<UsersModel>>.Exception("系统异常", null);
            }
        }

        /// <summary>
        /// 获取用户角色下拉列表
        /// </summary>
        /// <returns></returns>
        public ReturnData<List<DropDownListModel<int>>> GetRoleTypeDropDownList()
        {
            List<DropDownListModel<int>> result = new List<DropDownListModel<int>>();
            foreach (var item in Enum.GetValues(typeof(RoleTypeEnum)))
            {
                if (item.ToString() == RoleTypeEnum.系统管理员.ToString())
                {
                    continue;
                }

                result.Add(new DropDownListModel<int>() { DisplayMember = item.ToString(), ValueMember = (int)item });
            }
            return ReturnDataHelper<List<DropDownListModel<int>>>.Success("操作成功", result);
        }

        /// <summary>
        /// 修改管理员状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> ModifyUserEnable(ModifyUserEnableInput input)
        {
            try
            {
                AdminsEntity user = _adminService.FindEntity(input.ID);
                if (user == null)
                {
                    return ReturnDataHelper<bool>.NoExists("管理员信息不存在", false);
                }
                if (user.RoleType == (int)RoleTypeEnum.系统管理员)
                {
                    return ReturnDataHelper<bool>.Fail("系统管理员信息不允许修改", false);
                }

                _adminService.ModifyUserEnable(input.ID, input.Enable);

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("修改管理员状态,ModifyUserEnable", ex);
                return ReturnDataHelper<bool>.Exception("系统异常", false);
            }
        }

        /// <summary>
        /// 修改管理员信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> EditUser(EditUserInput input)
        {
            try
            {
                AdminsEntity entity = _adminService.FindEntity(input.ID);
                if (entity == null)
                {
                    return ReturnDataHelper<bool>.NoExists("管理员信息不存在", false);
                }
                if (entity.RoleType == (int)RoleTypeEnum.系统管理员)
                {
                    return ReturnDataHelper<bool>.Fail("系统管理员信息不允许修改", false);
                }

                entity.UserName = input.UserName;
                entity.Email = input.Email;
                entity.RoleType = input.RoleType;
                _adminService.EditUserInfo(entity);

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("修改管理员信息,EditUser", ex);
                return ReturnDataHelper<bool>.Exception("系统异常", false);
            }
        }

        /// <summary>
        /// 删除管理员信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> DeleteUser(DeleteUserInput input)
        {
            try
            {
                AdminsEntity entity = _adminService.FindEntity(input.ID);
                if (entity == null)
                {
                    return ReturnDataHelper<bool>.NoExists("管理员信息不存在", false);
                }
                if (entity.RoleType == (int)RoleTypeEnum.系统管理员)
                {
                    return ReturnDataHelper<bool>.Fail("系统管理员信息不允许修改", false);
                }

                _adminService.Delete(input.ID);

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("删除管理员信息,DeleteUser", ex);
                return ReturnDataHelper<bool>.Exception("系统异常", false);
            }
        }

        /// <summary>
        /// 获取管理后台菜单信息
        /// </summary>
        /// <returns></returns>
        public ReturnData<List<AdminBetterRouterModel>> GetAdminBetterManageMenu()
        {
            List<AdminBetterRouterModel> result = new List<AdminBetterRouterModel>();
            try
            {
                string userId = ManagerUnit.GetCurrentID();
                if (string.IsNullOrEmpty(userId))
                {
                    return ReturnDataHelper<List<AdminBetterRouterModel>>.NeedLogin("请登录后再操作", null);
                }

                AdminsEntity user = _adminService.FindEntity(userId);

                #region 菜单
                //首页
                AdminBetterRouterModel rootRouter = new AdminBetterRouterModel()
                {
                    Path = "/",
                    Component = "Layout",
                    Redirect = "/",
                    Sort = 1,
                    Meta = new AdminBetterRouterMeta()
                    {
                        Title = "首页",
                        Icon = "home"
                    }
                };
                rootRouter.Children.Add(new AdminBetterRouterModel()
                {
                    Path = "/",
                    Name = "/",
                    Component = "@/views/index",
                    Sort = 1,
                    Meta = new AdminBetterRouterMeta()
                    {
                        Title = "首页",
                        Icon = "home",
                        NoKeepAlive = false,
                        Affix = true
                    }
                });
                result.Add(rootRouter);

                //配置信息
                AdminBetterRouterModel configRouterRoot = new AdminBetterRouterModel()
                {
                    Path = "/ConfigRoot",
                    Component = "Layout",
                    Redirect = "projectInfoIndex",
                    Sort = 2,
                    Meta = new AdminBetterRouterMeta()
                    {
                        Title = "配置信息",
                        Icon = "file"
                    }
                };
                configRouterRoot.Children.Add(new AdminBetterRouterModel()
                {
                    Path = "/projectInfoIndex",
                    Name = "projectInfoIndex",
                    Component = "@/views/projectConfig/projectInfoIndex",
                    Sort = 1,
                    Meta = new AdminBetterRouterMeta()
                    {
                        Title = "项目信息",
                        Icon = "project-diagram",
                        NoKeepAlive = false
                    }
                });
                if (user.RoleType == (int)RoleTypeEnum.系统管理员)
                {
                    configRouterRoot.Children.Add(new AdminBetterRouterModel()
                    {
                        Path = "/recycleProjectInfoIndex",
                        Name = "recycleProjectInfoIndex",
                        Component = "@/views/projectConfig/recycleProjectInfoIndex",
                        Sort = 2,
                        Meta = new AdminBetterRouterMeta()
                        {
                            Title = "项目回收站",
                            Icon = "recycle",
                            NoKeepAlive = false
                        }
                    });
                }
                result.Add(configRouterRoot);

                //设置
                AdminBetterRouterModel settingRouterRoot = new AdminBetterRouterModel()
                {
                    Path = "/SettingRoot",
                    Component = "Layout",
                    Redirect = "userIndex",
                    Sort = 3,
                    Meta = new AdminBetterRouterMeta()
                    {
                        Title = "设置",
                        Icon = "tools"
                    }
                };
                if (user.RoleType == (int)RoleTypeEnum.系统管理员 || user.RoleType == (int)RoleTypeEnum.超级管理员)
                {
                    settingRouterRoot.Children.Add(new AdminBetterRouterModel()
                    {
                        Path = "/userIndex",
                        Name = "userIndex",
                        Component = "@/views/sysSetting/user/index",
                        Sort = 1,
                        Meta = new AdminBetterRouterMeta()
                        {
                            Title = "管理员列表",
                            Icon = "user-cog",
                            NoKeepAlive = false
                        }
                    });
                }

                settingRouterRoot.Children.Add(new AdminBetterRouterModel()
                {
                    Path = "/loginLog",
                    Name = "loginLog",
                    Component = "@/views/sysSetting/loginlog/index",
                    Sort = 2,
                    Meta = new AdminBetterRouterMeta()
                    {
                        Title = "登录日志",
                        Icon = "record-vinyl",
                        NoKeepAlive = false
                    }
                });
                settingRouterRoot.Children.Add(new AdminBetterRouterModel()
                {
                    Path = "/personalCenter",
                    Name = "personalCenter",
                    Component = "@/views/sysSetting/personalCenter",
                    Sort = 3,
                    Meta = new AdminBetterRouterMeta()
                    {
                        Title = "个人中心",
                        Icon = "person-booth",
                        NoKeepAlive = false
                    }
                });
                result.Add(settingRouterRoot);
                #endregion

                return ReturnDataHelper<List<AdminBetterRouterModel>>.Success("", result);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("获取管理后台菜单信息,GetAdminBetterManageMenu", ex);
                return ReturnDataHelper<List<AdminBetterRouterModel>>.Exception("系统异常", null);
            }
        }
    }
}
